<?php
// +----------------------------------------------------------------------
// | 会员卡消费对接
// +----------------------------------------------------------------------
// | Author: TongBC <501468940@qq.com>
// +----------------------------------------------------------------------
// | Date  : 2015/05/28
// +----------------------------------------------------------------------
$data = file_get_contents('php://input');

include_once '/var/www/html/new/com.inc.php';
include_once '/var/www/html/new/d/class/Terminal_Check_Socket.class.php';

$ac = $GLOBALS['_ac'];
$pw = $GLOBALS['_pw'];
$s  = new SoapClient(null,array("location" => "http://localhost/open/openService/pft_insideMX.php","uri" => "www.16u.com?ac_16u=$ac|pw_16u=$pw|auth_16u=true"));

// $data = '{"Action":"purchase","Terminal":8325,"sendData":"3522211489,\u6211\u662f\u53f8\u673a,123456,1,17536,1,6970"}';
// $data = '{"Action":"ticket","Terminal":8325,"cardSerial":"3522211489"}';

write_logs($data);
function write_logs($txt){
	$file = '/var/www/html/new/d/api/logs/terminal/terminal_sale_data_'.date('Ym').'.txt';
	$fp = fopen($file,"a");
	flock($fp, LOCK_EX);
	fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
	flock($fp, LOCK_UN);
	fclose($fp);
}


$_REQUEST = $request = json_decode($data, true);
$action   = $request['Action'];
$memcard  = new MemberCardAuth($s);
// if($request['Terminal']==8325){
	// include_once '/var/www/html/new/d/api/member_card_consume_dev.php';
	// $memcard = new MemberCardAuth_dev($s);
// }

switch($action){
	case 'ticket':$memcard->saleTickets($request['Terminal'], $request['cardSerial']);break;// 获取产品
	case 'purchase':$memcard->orderSubmit($request['Terminal'], $request['sendData']);break;// 下单消费
	default:break;
}


class MemberCardAuth{
	

	public $inSide = null;// 内部接口
	
	public function __construct($s){
		$this->inSide = $s;
	}
	
	
	public function Authentication($terminal, $card_no){
		
		// 获取会员卡绑定的平台账号
		$sql = "select c.id,c.memberID,c.status,c.password,c.derror,c.physics_no,m.dname,m.mobile,m.account,c.apply_did from pft_member_card c left join pft_member m on c.memberID=m.id where c.physics_no='$card_no' limit 1";
		
		if(strpos($card_no, '|')!==false){// 是身份证重组语句
			$idCard_a = explode('|', $card_no);
			$idCard_b = explode(',', $idCard_a[1]);
			$idCard_s = $idCard_b[0];
			$GLOBALS['le']->query("select fid from pft_member_extinfo where id_card_no='$idCard_s' limit 1");
			if(!$GLOBALS['le']->fetch_assoc()) $this->Response(209, '身份证未开通');
			$fid = $GLOBALS['le']->f('fid');
			$sql = "select c.id,c.memberID,c.status,c.password,c.derror,c.physics_no,m.dname,m.mobile,m.account,c.apply_did from pft_member_card c left join pft_member m on c.memberID=m.id where c.memberID=$fid limit 1";
		}
		
		$GLOBALS['le']->query($sql);
		$c_info = $GLOBALS['le']->fetch_assoc();
		if(!$c_info) $this->Response(201, '会员卡未开通');
		if($c_info['status']==1) $this->Response(202, '会员卡已挂失');
		if($c_info['status']==2) $this->Response(202, '会员卡已禁用');
		if($c_info['status']==3) $this->Response(202, '会员卡已冻结');
		if($c_info['status']==4) $this->Response(202, '会员卡已废弃');
		return $c_info;
	}
	
	// 获取分销商可购买票类
	public function saleTickets($terminal, $card_no){
		
		$c_info = $this->Authentication($terminal, $card_no);

		$pid = 0;// 产品ID
		$fid = $c_info['memberID'];  // 自己的ID 
		$aid = $c_info['apply_did']; // 供应商ID
		
		$account   = $c_info['account'];
		$ordertel  = $c_info['mobile'];
		$ordername = $c_info['dname'];
		
		// 获取 salerid
		$sql = "select id,salerid,apply_did from uu_land where terminal=$terminal order by id desc limit 1";
		$GLOBALS['le']->query($sql);
		$GLOBALS['le']->fetch_assoc();
		$salerid = $GLOBALS['le']->f('salerid');

		// 获取门票
		$sales = array(); $count = 0;
		$sql = "select t.title,t.id as tid,e.pid,t.landid from pft_p_apply_evolute e inner join uu_products p on p.id=e.pid left join ";
		$sql.= "uu_jq_ticket t on t.pid=e.pid where p.p_status=0 and p.apply_limit=1 and e.sid=$aid and e.fid=$fid and e.status=0 and t.pay=1 and p.salerid=$salerid ";
		$sql.= "order by verify_time desc";
		$GLOBALS['le']->query($sql);
		while($row=$GLOBALS['le']->fetch_assoc()){
			$resxml = $this->inSide->Dynamic_Price_And_Storage($account, $row['pid'], date('Y-m-d'), 1, 0, 0, $aid);
			if($resxml==105 || $resxml==1065) continue;// 过滤没有价格的票
			$simxml  = simplexml_load_string($resxml);
			$sales[] = $row['tid'];
			$sales[] = $row['title'];
			$sales[] = (string)$simxml->Rec->UUsprice/100;
			$sales[] = $aid;
			$count   = $count+1;
		}
		if($count==0) $this->Response(200,'');
		$this->Response(200,$ordername.','.$ordertel.','.$count.','.implode(',', $sales));
	}
	
	// 下单消费
	public function orderSubmit($terminal, $cData){
		
		// 处理接收数据
		$recvData    = $cData;
		$recvData 	 = explode(',', $recvData);
		$card_no  	 = $recvData[0];// IC物理卡号
		$password 	 = $recvData[2];// IC消费密码
		$dname    	 = $recvData[1];// 会员名称
		$totalTicket = $recvData[3];// 总购票类数
		
		$c_info = $this->Authentication($terminal, $card_no);
		
		$card_no    = $c_info['physics_no'];
		$fid        = $c_info['memberID']; // 自己的ID 
		$ordertel   = $c_info['mobile'];
		$ordername  = $c_info['dname'];
		$account    = $c_info['account'];
		$derror     = $c_info['derror'];   // 消费密码错误次数
		$dbPass     = $c_info['password'];
		$note_type  = $c_info['memberID'];
		$cardSerial = $c_info['memberID']; // IC卡显示编号
		

		// 获取 salerid
		$sql = "select id,salerid,apply_did,title from uu_land where terminal='$terminal' order by id desc limit 1";
		$GLOBALS['le']->query($sql);
		$GLOBALS['le']->fetch_assoc();
		$salerid = $GLOBALS['le']->f('salerid');
		$ltitle  = $GLOBALS['le']->f('title');
		
		$pInfos   = array();
		$pInfos_a = array_slice($recvData, 4);
		$pInfos   = array_chunk($pInfos_a, 3);
		
		$totalPrice = 0;
		$totalTnum = 0;// 总票数
		$order = $order_info = $c_infos = array();// 保存下单数据

		// 预定时间
		$begintime = date('Y-m-d 00:00:00');
		$endtime   = date('Y-m-d 23:59:59');

        define('DEFAULT_WECHAT_APPID', 'wx678d02326b6ba9d9'); //三亚先行公众号

		// 多票处理
		foreach($pInfos as $key=>$row){
			
			$tid  = $row[0]; // 门票ID
			$tnum = $row[1]; // 预定数量
			$aid  = $row[2]; // 供应商ID 

			
			// 获取产品数据
			$str="select p.id as pid,p.apply_limit,p.salerid,p.p_status,p.apply_did,l.id as lid,l.title as ltitle,l.p_type,t.id as tid,t.tprice,t.pay,t.title as ttitle,t.delaydays,t.ddays,t.buy_limit_low,t.buy_limit_up,t.status,t.storage_open,t.storage,t.getaddr,f.dhour,f.series_model,f.mdays,f.v_ID_support from uu_products p left join uu_jq_ticket t on p.id=t.pid left join uu_land l on p.contact_id=l.id left join uu_land_f f on p.id=f.pid where t.id=$tid limit 1";
			
			$GLOBALS['le']->query($str);
			$p_info = $GLOBALS['le']->fetch_assoc();
			
			// 产品购买限制判断
			if($tnum<$p_info['buy_limit_low'])  $this->Response(204,"必须购买".$p_info['buy_limit_low']);
			if($p_info['buy_limit_up']!=0 && $tnum>$p_info['buy_limit_up'])  $this->Response(204,"购买张数不能大于".$p_info['buy_limit_up']);
			if($p_info['apply_limit']!=1) $this->Response(102, '产品未通过审核');
			
			
			// 景区配置限制
			$sql = "select * from pft_prod_restrict where pid={$p_info['pid']} order by id desc limit 1";
			
			$GLOBALS['le']->query($sql);
			if($GLOBALS['le']->fetch_assoc()){
				$daily_buy_limit = $GLOBALS['le']->f('daily_buy_limit');// 每天购买总数
				$buy_interval = $GLOBALS['le']->f('buy_interval');      // 两次购买间隔
				$buy_num_limit = $GLOBALS['le']->f('buy_num_limit');    // 每次购买上限
				$returnSize = 1;
				if($daily_buy_limit!=-1){
					$returnSize = $daily_buy_limit + 1;
					$simxml = $this->inSide->Order_Globle_Search('', $fid, '', $tid, '', '', $begintime, $endtime, '', '', '', '', '', '', '', '', '', '', 1, 1, 0, $returnSize, 0, 0, 2, 0, '', 0, '', '', '', 0, 0, 0, '', '');
					$simxml_o = simplexml_load_string($simxml);
					if(count($simxml_o)>=$daily_buy_limit) $this->Response(206,'会员卡购买次数已达上限值'.$daily_buy_limit);
				}
		
				if($buy_interval!=-1){// 购买间隔
					
					if($daily_buy_limit==-1){
						$simxml = $this->inSide->Order_Globle_Search('', $fid, '', $tid, '', '', $begintime, $endtime, '', '', '', '', '', '', '', '', '', '', 1, 1, 0, $returnSize, 0, 0, 2,  0, '', 0, '', '', '', 0, 0, 0, '', '');
						$simxml_o = simplexml_load_string($simxml);
					}

					$lastOrder = $simxml_o->Rec[0];
					$lastSubmitOrder = (string)$lastOrder->UUordertime;
					$diffTime = $buy_interval*60 - (time()-strtotime($lastSubmitOrder));
					
					$wait = floor($diffTime / 3600).'小时'.floor(($diffTime % 3600) / 60).'分'.($diffTime % 60).'秒';
					if($diffTime>0) $this->Response(205,'距离下次购买还剩'.$wait);
				}
				
				if($buy_num_limit!=-1 && $tnum>$buy_num_limit) $this->Response(204,"票数大于单次购买限制$buy_num_limit");
				
			}

			// 是否有购买权限
			$auth = authCheck($fid, $aid, $p_info);
			if(!$auth['auth']) $this->Response(102, '产品无权限购买');
			
			// 检测套票子票
			if($p_info['p_type']=='F'){
				$chkResult = \pft\Prod\Sale::PackageTicketCheck($this->inSide, $pid, $fid, $aid, substr($valid_start,0,10), $num);
				if($chkResult['code']!=200) $this->Response(107, '子票出错');
			}

			
			$simxml = $this->inSide->Dynamic_Price_And_Storage($account, $p_info['pid'], substr($begintime,0,10), 1, 0, 1,$aid);
			if($simxml==105 || $simxml==1065) $this->Response(103, '产品无价格日期');
					
			// 库存判断
			$simxml_o = simplexml_load_string($simxml);
			$storage  = $simxml_o->Rec->UUstorage;
			if($storage>-1 && $storage<$tnum) $this->Response(104, "库存不足,剩余库存:$storage");
			
			// 订单金额
			$tprice = (string)$simxml_o->Rec->UUsprice;
			$totalMoney = $tprice * $tnum; // 一个票总价
			$totalPrice = $totalPrice + $totalMoney;// 所有票总价
			$totalTnum = $totalTnum + $tnum;
			$order_info = array(
				'fid'        => $fid,
				'lid'        => $p_info['lid'],
				'tid'        => $tid,
				'pid'        => $p_info['pid'],
				'tprice'     => $tprice,
				'tnum'       => $tnum,
				'totalMoney' => $totalMoney,
				'begintime'  => $begintime,
				'endtime'    => $endtime,
				'salerid'    => $p_info['salerid'],
				'aid'        => $aid,
				'series'     => '',
				'ordername'  => $ordername,
				'ordertel'   => $ordertel,
				'ttitle'     => $p_info['ttitle'],
				'ordermode'  => 9
			);

			if($key==0){
				$order = $order_info;
			}else{
				$c_infos[] = $order_info;
			}
		}


		// 会员卡使用授信支付
		$fundXml  = $this->inSide->PFT_Member_Fund($fid, 1, $aid);
		$fundXml1 = simplexml_load_string($fundXml);
		$fundXml  = $this->inSide->PFT_Member_Fund($fid, 2, $aid);
		$fundXml2 = simplexml_load_string($fundXml);
		$canUseMoney = (string)$fundXml1->Rec->UUkmoney + (string)$fundXml2->Rec->UUbasecredit;
		$surplus = $canUseMoney - $totalPrice;// 剩余
		if($surplus<0) $this->Response(106,'可供应余额不足');
		$surplus = $surplus/100;
		
		
		
		// 优惠券使用检测
		$coupon = array();$coupon_mc_id = 0;
		if(count($c_infos)==0){
			$today = date('Y-m-d');
	
			$sql = "select mc.id,mc.coupon_id,c.coupon_value,c.limit_use from pft_member_coupon mc left join pft_coupons c on mc.coupon_id=c.id where mc.fid=$fid and mc.aid=$aid and mc.dstatus=0 and c.pid in ({$order['pid']},0) and c.condition<=$totalPrice and start_date<='$today' and end_date>='$today' and c.id<>27 order by coupon_value desc limit 1";
			
			if($order['pid']==22110){// 定制可乐券
				$coupon_mc_id = 27;
				$sql = "select mc.id,mc.coupon_id,c.coupon_value,c.limit_use from pft_member_coupon mc left join pft_coupons c on mc.coupon_id=c.id where mc.fid=$fid and mc.aid=$aid and mc.dstatus=0 and c.id=$coupon_mc_id and c.condition<=$totalPrice and start_date<='$today' and end_date>='$today' order by coupon_value desc limit 1";
			}
			
			$GLOBALS['le']->query($sql);
			if($GLOBALS['le']->fetch_assoc()){
				
				$coupon_total = 1;
				$coupon_id    = $GLOBALS['le']->f('coupon_id');
				$coupon_mc_id = array($GLOBALS['le']->f('id'));
				$coupon_value = $GLOBALS['le']->f('coupon_value');
				
				// 优惠券使用限制 0 不限 1 一次1张 2 随门票总数
				if($GLOBALS['le']->f('limit_use')==2){
					$sql = "select mc.id,c.coupon_value from pft_member_coupon mc left join pft_coupons c on mc.coupon_id=c.id where mc.fid=$fid and mc.aid=$aid and mc.dstatus=0 and c.pid in ({$order['pid']},0) and c.condition<=$totalPrice and start_date<='$today' and end_date>='$today' and c.id=$coupon_id limit ".$order['tnum'];
					$GLOBALS['le']->query($sql);
					while($row=$GLOBALS['le']->fetch_assoc()) $coupon_a[$row['id']] = $row;
					$coupon_total = count($coupon_a);
				}
				
				// 计算优惠后的总金额
				$order['totalMoney'] = $order['totalMoney'] - ($coupon_value*$coupon_total);
				if($order['totalMoney']<=0) $order['totalMoney'] = 'A';
				if($coupon_total>1) $coupon_mc_id = array_keys($coupon_a);

			}
		}
		
		

        $r = $this->inSide->Group_Order_Submit($order['fid'], $order['lid'], $order['tid'],$order['begintime'],$order['endtime'], $order['tprice'],$order['tnum'],$order['totalMoney'], $order['ordername'], $order['ordertel'],"", $order['salerid'], $order['aid'], 2, $order['ordermode'], '', 0, $order['series'], 1);
		
		if($r<100000){
			if($r==222) $this->Response(106, '上级资金账户不足');
			$this->Response(106, '下单接口出错:'.$r);
		}
		
		
		// 更改会员优惠券使用状态
		if($coupon_total){
			$couponMids = implode(',', $coupon_mc_id);
			$sql = "update pft_member_coupon set dstatus=2,ordernum=$r where id in ($couponMids) and fid=$fid limit $coupon_total";
			if(!$GLOBALS['le']->query($sql)) $this->write_logs("优惠券状态更改失败:$r:$sql", 'terminal_sale_coupon_'.date('Ym').'.txt');
			
			// 活动推送
			$data = base64_encode(json_encode(array('ordernum' => $r, 'pid' => $pid, 'mid' => $fid)));
            @file_get_contents('http://localhost/wx/game/share_pages/send_coupon.php?data='.$data);
		}
		
		// 联票下单
        if(count($c_infos)>0) $this->subOrder($c_infos, $r);
		
		// 获取订单信息
		$option = array("","","","","","","","","","","","",$r,"","","","","",1,1,0,1,"","","","","","","","", "",0,1);
		$resxml = $this->inSide->__call('Order_Globle_Search', $option);
		$simxml = simplexml_load_string($resxml);
		
		// 返回数据
		array_unshift($c_infos,$order);
		$ordertime = date('Y-m-d H:i:s');
		$response[] = $surplus;	 // 会员卡余额
		$response[] = $ltitle;	 // 网点名称
		$response[] = $ordername;// 会员姓名
		$response[] = $ordertel; // 会员手机
		$response[] = $r;      	 // 订单编号
		$response[] = $ordertime;// 下单时间
		$response[] = $ordertime;// 验证时间
		$response[] = count($c_infos);// 总购票类数量

        $itemData = $itemData_sms = '';
		foreach($c_infos as $row){
			$response[] = $row['tid'];
			$response[] = $row['ttitle'];
			$response[] = $row['tnum'];
			$itemData .= "\n{$row['ttitle']}:{$row['tnum']} 张；";
			$itemData_sms.= "{$row['ttitle']}{$row['tnum']}张，";
		}
		
        $totalPrice = $totalPrice / 100;
		if($note_type==1){ // 消费通知类型    0 不通知 1 微信通知 2 短信
			include_once '/var/www/html/new/d/class/OrderSmsManual.class.php';
			$smsManual = $smsManual = new \PFT\SMS\OrderSmsManual($this->inSide);
			if($wx_open_id = $smsManual->WxNotifyChk($fid, 0, true)) 
			$smsManual->WxNotifyCustomer($wx_open_id, $begintime, $ordername, $ltitle, $itemData, $r, $totalPrice);
		}elseif($note_type==2){
			$consume_s = ($daily_buy_limit==-1) ? '不限':($consume_s-1).'次';
			$smstpl = "您的会员卡{$cardSerial}，{$begintime}，成功预订{$itemData_sms}，消费{$totalPrice}元，剩余{$surplus}元，当日剩余消费次数{$consume_s}";
			$this->inSide->Send_SMS_V($ordertel, $smstpl);
		}
		

		// 验证订单
		$ordernum = (string)$simxml->Rec->UUordernum;
		$tc = Terminal_Check_Socket::connect();
		$chResult = $tc->Terminal_Check_In_Voucher($terminal, $salerid, (string)$simxml->Rec->UUcode, array('vCmd'=>499,'vMode'=>8));
		$logtxt = "订单验证:$ordernum,验证数据[".json_encode(array($terminal, $salerid, (string)$simxml->Rec->UUcode, array('vCmd'=>499,'vMode'=>8)))."],验证结果[".json_encode($chResult)."]";
		$this->write_logs($logtxt, 'termial_sale_check_'.date('Ym').'.txt');
		if($chResult['state']=='fail')$this->Response(201, $chResult['msg']);
		
		// 缓存输出日志
		if($terminal==10379){
			$cache_file = '/var/www/html/new/d/api/logs/terminal/terminal_sale_output_'.date('Ym').'.txt';
			$cache_data = file_exists($cache_file) ? json_decode(file_get_contents($cache_file), true):array();
			$cache_data[$card_no.'_'.$terminal] = implode(',', $response).','.(string)$simxml->Rec->UUcode;
			file_put_contents($cache_file,json_encode($cache_data));
		}
		$this->Response(200, implode(',', $response));
	}
	
	public function subOrder($c_infos,$r){
        $str="update uu_order_fx_details set concat_id='$r' where orderid='$r' limit 1";
        $GLOBALS['le']->query($str);
        foreach($c_infos as $order){
			$c_r=$this->inSide->Group_Order_Submit($order['fid'], $order['lid'], $order['tid'],$order['begintime'],$order['endtime'], $order['tprice'],$order['tnum'],$order['totalMoney'], $order['ordername'], $order['ordertel'],"", $order['salerid'], $order['aid'], 2, $order['ordermode'], '', 0, $order['series'], 1, $r);
            if($c_r>=100000){
                $str="update uu_order_fx_details set concat_id='$r' where orderid='$c_r'";
                $GLOBALS['le']->query($str);
            }else{		
				$this->Response(107, "联票子票下单出错:$c_r".json_encode($order));
            }
        }
    }
	
	
	// 消息输出
	public function Response($code, $msg){
		$suffix  = date('Ymd');
		$logfile = ($code==200) ? "terminal_sale_success_$suffix.txt":"terminal_sale_error_$suffix.txt";
		$this->write_logs("$code|$msg|".json_encode($_REQUEST), $logfile);
		$GLOBALS['le']->close();
		exit("$code|$msg");
	}
	
	
	// 日志记录
    public function write_logs($txt,$file){
        $fullPath = '/var/www/html/new/d/api/logs/terminal/'.$file;
        $fp = fopen($fullPath,"a");
        flock($fp, LOCK_EX);
        fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
        flock($fp, LOCK_UN);
        fclose($fp);
    }

}

// 购买权限认证 分销商ID 上级供应ID 产品ID
function authCheck($fid,$aid,$p_info){
    $arr = array('self'=>false,'auth'=>false);
    $pid = $p_info['pid'];
    if($p_info['apply_did']==$fid){ // 自供应
        $arr['self'] = true;
        $arr['auth'] = true;
        return $arr;
    }
    if($p_info['apply_did']==$aid){ // 直接供应
        $sql="select pids from `pft_product_sale_list` where fid=$fid and aid=$aid LIMIT 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $pids=$GLOBALS['le']->f("pids");
        if($pids=='A') $arr['auth'] = true;
        if(in_array($pid,explode(",",$pids)))$arr['auth'] = true;
        return $arr;
    }
    // 多手供应
    $sql="select * from pft_p_apply_evolute where pid=$pid and sid=$aid and fid=$fid and status=0 limit 1";
    $GLOBALS['le']->query($sql);
    if($row=$GLOBALS['le']->fetch_assoc())$arr['auth'] = true;
    return $arr;
}


// 101:账号禁用
// 102:产品无权限购买
// 103:产品无价格日期
// 104:产品无库存
// 105:产品购买下限及上限
// 106:账户资金不充足
// 107:其他套票情况


// 201:会员卡未开通
// 202:会员卡状态不正常   冻结/禁用/挂失/废弃
// 203:消费密码错误
// 204:购买票数大于单次购买数量
// 205:购买间隔
// 206:单日购买次数已达上限值
// 207:产品配置不允许使用会员卡购买


